<!--
°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
° 	HONORE Perrine
° 	GIOVANETTI Romain
°
° 	Master 2 - E-services TWA Project
°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°°
-->
<!doctype html>
<html>
<head>
	<meta charset='UTF-8' />
	<style>
		input, textarea {border:1px solid #CCC;margin:0px;padding:0px}

		#body {max-width:800px;margin:auto}
		#log {width:100%;height:400px}
		#message {width:100%;line-height:20px}
	</style>
	<script type="text/javascript" src="./javascript/mirrorjs.min.js"></script>
	<script type="text/javascript" src="./websocketserver.js"></script>
	<script type="text/javascript" src="./javascript/tools.js"></script>
	<script type="text/javascript" src="./javascript/settings.js"></script>
	<script type="text/javascript" src="./javascript/json2.js"></script>
	<script type="text/javascript" src="./javascript/objects/Client.js"></script>
	<script type="text/javascript" src="./javascript/objects/ClientsList.js"></script>
	<script type="text/javascript" src="./javascript/objects/Messages.js"></script>
	<script type="text/javascript" src="./javascript/objects/MessagesList.js"></script>
	<script type="text/javascript" src="./javascript/objects/Conversation.js"></script>
	<script type="text/javascript" src="./javascript/objects/ConversationsList.js"></script>
	<script type="text/javascript" src="./createDatabase.js"></script>

	<!-- Pas Temporaire -->
	<script type="text/javascript" src="./javascript/initserver.js"></script>

	<script>
		
		var baseIOHU = openDatabase('IOHUdb', '1.0', 'DataBase tchat', 2 * 1024 * 1024);

		var Server;

		var listeDesClients = new o_clientslist();

		var listeDesConversations = new o_conversationslist();

		var listeDesMessages = new o_messageslist();



		function log( text ) {
			$log = $('#log');
			//Add text to log
			$log.append(($log.val()?"\n":'')+text);
			//Autoscroll
			$log[0].scrollTop = $log[0].scrollHeight - $log[0].clientHeight;
		}

		function send( text ) {
			Server.send( 'message', text );
		}

		$(document).ready(function() {
			log('Connecting...');
			Server = new FancyWebSocket('ws://127.0.0.1:9300');

			$('#message').keypress(function(e) {
				if ( e.keyCode == 13 && this.value ) {
					log( 'You: ' + this.value );
					send( this.value );

					$(this).val('');
				}
			});

			//Let the user know we're connected
			Server.bind('open', function() {
				log( "Connected." );
			});

			//OH NOES! Disconnection occurred.
			Server.bind('close', function( data ) {
				log( "Disconnected." );
			});

			//Log any messages sent from server
			Server.bind('message', function( payload ) {
				log( payload );
				var messageRecu = payload.split(' __ws__ ')[1];
				var clientId = payload.split(' __ws__ ')[0].split("").reverse().join("");

				/* Si une commande est reçue, on la traite */
				if(messageRecu.charAt(0) == '/')
				{
					var commande = messageRecu.split('#')[0];
					switch (commande) {
						 case "/openConnection":
						 	send("/serveurReady#" + salt+"#"+clientId);
						 break;

						 case "/login":
							var login = messageRecu.split('#')[1];
							var password = messageRecu.split('#')[2];

							verbose("Demande d'auth. ("+login+", "+password+")");

							var clientDemandeur = getClientByLogin(listeDesClients, login);
							if(clientDemandeur!= null)
							{
								if(isPasswordCorrect(clientDemandeur, password) == 1)
								{
									clientDemandeur.client_onlineId = clientId.split(">")[1];
									setStatus(clientDemandeur.client_id, 1, baseIOHU, listeDesClients);
									send("/loginOK#"+clientId);
								}
								else
								{
									verbose("Mauvais mot de passe envoyé.");
									send("/serveurReady#" + salt+"#"+clientId);
								}
							}
							else
							{
								verbose("Client inexistant.");
								send("/serveurReady#" + salt+"#"+clientId);
							}
						 
						 break;

						 case "/getListAmis":
						 	listeDesConnectes = getOnlineClientsList(listeDesClients);
						 	var myJsonString = JSON.stringify(listeDesConnectes);
						 	send("/listeDesConnectes#" + myJsonString+"#"+clientId);
						 break;

						 case "/getConversationWith":
						 	var userAId = getIdByOnlineID(listeDesClients,clientId.split(">")[1]);
						 	var userA = getClientById(listeDesClients,userAId).client_nickname;
						 	var userB = messageRecu.split('#')[1];
						 	var conversationId = getConversationId(listeDesConversations, userA, userB);
						 	if(conversationId == null)
						 	{
						 		conversationId = createConversation(listeDesConversations,userA,userB,baseIOHU);
						 	}
						 	var messages = getMessagesFromTwoUsers(listeDesMessages, conversationId);
						 	var myJsonString = JSON.stringify(toObject(messages));
						 	send("/conversationWith#"+userB + "#"+myJsonString+"#"+clientId);
						 break;

						 case "/messageAEnvoyerA":
						 	var userAId = getIdByOnlineID(listeDesClients,clientId.split(">")[1]);
						 	var userA = getClientById(listeDesClients,userAId).client_nickname;
						 	var userB = messageRecu.split('#')[1];
						 	var conversationId = getConversationId(listeDesConversations, userA, userB);
						 	if(conversationId == null)
						 	{
						 		conversationId = createConversation(listeDesConversations,userA,userB, baseIOHU);
						 	}

							var ts = Math.round((new Date()).getTime() / 1000);
						 	createMessages(listeDesMessages,conversationId,userA, messageRecu.split('#')[2], ts, baseIOHU);
						 break;


						 /* /registerClient#username#password */
						 case "/registerClient":
						 	var userId = clientId.split(">")[1];

						 	createUser(listeDesClients, userId ,messageRecu.split('#')[1], messageRecu.split('#')[2], baseIOHU);
						 	console.dir(listeDesClients);
						 break;

						 case "/logout":
						 	var userId = getIdByOnlineID(listeDesClients,clientId.split(">")[1]);
						 	setStatus(userId,0, baseIOHU,listeDesClients);
						 break;
						 

						 default: 
						 	verbose("Commande invalide");
						 break;
					}
				}
				else
				{
					if(messageRecu == "isonline")
					{
						send("/yourIdIs#"+ clientId);
					}
					else if(messageRecu == "isoffline")
					{
						var userId = getIdByOnlineID(listeDesClients, payload.split(' __ws__ ')[0]);
						var client = getClientById(listeDesClients,userId);
						if(client != null)
						{
							updateUser(userId, 0, client.client_nickname, client.client_password, 0, baseIOHU, listeDesClients);
						}
					}
				}
			});

			initIOHUDatabase(baseIOHU);
			addClient(listeDesClients, listeDesConversations ,listeDesMessages, baseIOHU);
			Server.connect();
		});
	</script>
</head>

<body>
	<div id='body'>
		<textarea id='log' name='log' readonly='readonly'></textarea><br/>
		<!--<input type='text' id='message' name='message' />-->
	</div>
</body>

</html>